package com.kfm.hotel.controller;


import com.kfm.hotel.config.HotelProperties;
import com.kfm.hotel.ex.BussinessException;
import com.kfm.hotel.pojo.SysUser;
import com.kfm.hotel.service.SysUserService;
import com.kfm.hotel.util.Contains;
import com.kfm.hotel.util.R;
import com.kfm.hotel.util.SendEmailUtil;
import com.kfm.hotel.util.ValidEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class LoginController {

    @Autowired
    private HotelProperties properties;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SendEmailUtil sendEmailUtil;

    @GetMapping({"/", "/login"})
    public ModelAndView toLoginPage(HttpServletRequest request){
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("sys_title", properties.getTitle());
        return new ModelAndView("login");
    }

    @PostMapping("/login")
    public ModelAndView doLogin(@Validated SysUser sysUser, Errors errors, HttpSession session){
        ModelAndView modelAndView = new ModelAndView("login");
        SysUser user = sysUserService.login(sysUser);

        if (user == null){
            // 没有登录成功
            modelAndView.addObject("msg", "用户名或密码错误");
            return modelAndView;
        }

        // 登录成功
        session.setAttribute(Contains.LOGIN_USER, user);
        modelAndView.setViewName("redirect:index");
        return modelAndView;
    }

    @GetMapping("/index")
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView("index");
        return mv;
    }

    @GetMapping("/welcome")
    public ModelAndView welcome(){
        ModelAndView mv = new ModelAndView("welcome");
        return mv;
    }


    // 个人信息管理
    @GetMapping("/valid-email")
    public ModelAndView validEmail(){
        ModelAndView mv = new ModelAndView("valid-email");
        return mv;
    }

    @GetMapping("/send-email")
    public R sendEmail(HttpSession session) throws MessagingException {
        Object email_code = session.getAttribute("email_code");
        boolean flag = false;

        if (email_code == null){
            // 没有发送过
            flag = true;
        } else if(email_code != null){
            ValidEmail validEmail = (ValidEmail) email_code;
            if (validEmail.getStartTime() + 60 * 1000 > System.currentTimeMillis()){
                // 1 分钟后可再次发送
                flag = true;
            }
        }
        if (flag){
            SysUser sysUser = (SysUser) session.getAttribute(Contains.LOGIN_USER);
            String code = sendEmailUtil.vaildEmail(sysUser.getUsername());
            // 存起来
            long start = System.currentTimeMillis();
            session.setAttribute("email_code", new ValidEmail(code, start, start + 5 * 60 * 1000));
            return R.ok();
        }

        return R.failed("验证码已经发送，请勿重复点击");
    }

    @PostMapping("/valid-email")
    public R validEmail(String code, HttpSession session)  {
        ValidEmail email_code = (ValidEmail) session.getAttribute("email_code");
        if (email_code == null){
            throw new BussinessException("没有验证码");
        }
        if (email_code.getExpireTime() < System.currentTimeMillis()){
            session.removeAttribute("email_code");
            return R.failed("验证码过期");
        }

        if (!email_code.getCode().equals(code)){
            return R.failed("验证码错误");
        }
        session.removeAttribute("email_code");
        SysUser loginUser = (SysUser) session.getAttribute(Contains.LOGIN_USER);
        loginUser.setStatus(1);

        SysUser update = new SysUser();
        update.setId(loginUser.getId());
        update.setStatus(1);
        sysUserService.updateUser(update);
        return R.ok();
    }
}
